/**
 * @author YangDong
 * @description: 网络请求公共封装
 */
import fetch from './fetch';
import Toast from "../toast/Toast";
import Loading from "../loading/Loading";
import {AsyncStorage} from "react-native";

/**
 * 统一调用的post请求
 * @param url
 * @param params
 * @param tag
 * @returns {Promise}
 */
export const  post = async (tag,url,params)=>{
    let token = await AsyncStorage.getItem(global.tokenKey);
    return fetch(
        global.InterfaceIp+url,
        {
            method: 'POST',
            headers: {
                "Content-Type": 'application/json',
                "X-AUTH-TOKEN": token
            },
            body: JSON.stringify(params),
        },
        tag
    )
};

/**
 * 统一调用的get请求
 * @param url
 * @param params
 * @param tag
 * @returns {Promise}
 */
export const get = (tag,url,params)=>{
    let temp = '';
    for (let key in params) {
        temp = temp + key + '=' + params[key] + '&';
    }
    let http = global.InterfaceIp+url+'?'+temp.substring(0,temp.length-1);
    return fetch(http,{
        method: 'GET'
    },tag)
}

export const cancel = (tag)=>{
    fetch.abort(tag);
}

/**
 * 带loading的post请求
 * @param url 地址
 * @param params 参数
 * @param timeout 超时时间
 * @param tag
 * @param option
 * @returns {Promise.<*>}
 */
export function postWithLoading(tag,url,params,option){
    if(option === undefined){
        option = {showLoading: true}
    }else {
        if(option.showLoading === undefined){
            option = {showLoading: true};
        }
    };
    let timeout = 10;
    return new Promise((resolve, reject) => {
        let state = 0;//开始加载
        let showLoading = option.showLoading;
        let loadingMsg = option.loadingMsg?option.loadingMsg: '加载中...';
        let errMsg = option.errMsg?option.errMsg: '请求失败,请重试。';
        let overTimeMsg = option.overTimeMsg?option.overTimeMsg: '请求超时,请重试。';


        //超时后取消请求
        this.timer = setTimeout(()=>{
            state = 1;
            fetch.abort(tag);
            showLoading && Loading.hide();
            Toast.showError({message:overTimeMsg});
        },timeout * 1000);


        //开启一个Loading
        showLoading && Loading.show(Object.assign({
            backHandler: false,
            isCancel: false,
            loadingSize: 'small',
            loadingText: loadingMsg,
            onHidden: ()=>{
                if(state === 0){
                    this.timer && clearTimeout(this.timer);
                    fetch.abort(tag);
                }
            }
        },option.loadingOption));


        let result = null;
        post(tag,url,params)
            .then((request)=>{
                this.timer && clearTimeout(this.timer);
                if(request.ok){
                    return request.json();
                }
            })
            .then((json)=>{
                showLoading && Loading.hide();
                resolve(json);
            })
            .catch((err)=>{
                showLoading && Loading.hide();
                if(err.status !== 401){
                    Toast.showError({message:err.msg});
                }else {
                    Toast.showError({message:"登录已失效，请重新登录。"});
                }

                reject(err);
            })
    })
}

/**
 * 带loading的get请求
 * @param url 地址
 * @param params 参数
 * @param timeout 超时时间
 * @param tag
 * @param option
 * @returns {Promise.<*>}
 */
export async function getWithLoading(tag,url,params,option){
    if(option === undefined){ option= {}};
    let timeout = 10;
    return new Promise((resolve, reject) => {
        let state = 0;//开始加载
        let loadingMsg = option.loadingMsg?option.loadingMsg: '加载中...';
        let errMsg = option.errMsg?option.errMsg: '请求失败,请重试。';
        let overTimeMsg = option.overTimeMsg?option.overTimeMsg: '请求超时,请重试。';


        //超时后取消请求
        this.timer = setTimeout(()=>{
            state = 1;
            fetch.abort(tag);
            Loading.hide();
            Toast.showError({message:overTimeMsg});
        },timeout * 1000);


        //开启一个Loading
        Loading.show(Object.assign({
            backHandler: false,
            isCancel: false,
            loadingSize: 'small',
            loadingText: loadingMsg,
            onHidden: ()=>{
                if(state === 0){
                    this.timer && clearTimeout(this.timer);
                    fetch.abort(tag);
                }
            }
        },option.loadingOption));


        let result = null;
        post(tag,url,params)
            .then((request)=>{
                this.timer && clearTimeout(this.timer);
                if(request.ok){
                    return request.json();
                }
            })
            .then((json)=>{
                Loading.hide();
                resolve(json);
            })
            .catch((err)=>{
                Loading.hide();
                Toast.showError({message:err.msg||errMsg});
                reject(err);
            })
    })
}
const Request = {
    post: post,
    get: get,
    postWithLoading: postWithLoading,
    getWithLoading: getWithLoading,
    cancel: cancel
};

export default Request;